package com.xltx.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.xltx.oss.properties.AliyunOssProperties;
import com.xltx.oss.service.AliyunOssService;
import com.xltx.oss.model.AuthResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author liuyc
 * @ClassName AliyunOssServiceImpl
 * @Description
 * @Date 2021/12/16 14:31
 */
@Service
public class AliyunOssServiceImpl implements AliyunOssService {

    @Autowired
    private AliyunOssProperties aliyunOssProperties;

    public OSS getOssClient() {
        return new OSSClientBuilder().build(aliyunOssProperties.getEndpoint(), aliyunOssProperties.getAccessKey(), aliyunOssProperties.getSecretKey());
    }

    @Override
    public AuthResult ossAuth() {
        OSS ossClient = getOssClient();
        // 请填写您的 bucketname 。
        // host的格式为 bucketname.endpoint
        String host = "https://" + aliyunOssProperties.getBucket() + "." + aliyunOssProperties.getEndpoint();
        // callbackUrl为 上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
        // String callbackUrl = "http://88.88.88.88:8888";
        // 用户上传文件时指定的前缀。
        String formatDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String dir = formatDate + "/";
        AuthResult authResult = null;
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            authResult = new AuthResult();
            authResult.setAccessKey(aliyunOssProperties.getAccessKey());
            authResult.setPolicy(encodedPolicy);
            authResult.setSignature(postSignature);
            authResult.setDir(dir);
            authResult.setHost(host);
            authResult.setExpire(String.valueOf(expireEndTime / 1000));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        return authResult;
    }
}
